#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        k = min(k, n / 2);
        const int cnf = 0x3f3f3f3f;
        vector<vector<int>> dp1(n, vector<int>(k + 1, -cnf));
        auto dp2 = dp1;
        dp1[0][0] = -prices[0];
        dp2[0][0] = 0;
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= k; j++) {
                dp1[i][j] = max(dp1[i - 1][j], dp2[i - 1][j] - prices[i]);
                dp2[i][j] = dp2[i - 1][j];
                if (j >= 1)
                {
                    dp2[i][j] = max(dp2[i][j], dp1[i - 1][j - 1] + prices[i]);
                }
            }
        }
        int ret = 0;
        for (int j = 0; j <= k; j++) {
            ret = max(ret, dp2[n - 1][j]);
        }
        return ret;
    }
};